package com.stylefeng.guns.modular.charon.cdkey;

import java.security.MessageDigest;

public class SNFactory {
    private static MessageDigest md5 = null;
    private static char[] snCharArray = new char[]{
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', '1', '3', '4', '5', '6', '7', '8', '9'
    };

    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 用于获取一个String的md5值
     *
     * @return
     */
    private static String getMd5(String str) {
        byte[] bs = md5.digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString();
    }

    public static String getSN(String ip) {
        if (ip == null) return null;
        String input = ip.trim().toUpperCase();
        String md5Str = getMd5(input);
        String originalSNTxt = md5Str.substring(6, 26).toUpperCase();
        String SNTxt = "";
        int index = 0;
        for (int i = 0; i < originalSNTxt.length(); i++) {
            char c = originalSNTxt.charAt(i);

            if (c >= '0' && c <= '9') {
                index = (int) c - (int) '0';
            } else if (c >= 'A' && c <= 'V') {
                index = (int) c - (int) 'A' + 10;
            } else if (c >= 'W' && c <= 'Z') {
                index = (int) 'V' - (int) 'A' + 10;
            } else {
                index = -1;
            }

            SNTxt += snCharArray[index];
        }
        return SNTxt.substring(0, 5) + "-" + SNTxt.substring(5, 10) + "-" + SNTxt.substring(10, 15) + "-" + SNTxt.substring(15, 20);
    }

    public static boolean verifySN(String ipTxt, String sn) {
        String snTxt = getSN(ipTxt);
        if (snTxt == null || sn == null) return false;
        return snTxt.equals(sn.trim());
    }

    public static void main(String[] args) {
        /*String ip = "192.168.1.102:8090";
        String snTxt = "AHDPI-NCBDF-HQGJF-JMBDP";
        System.out.println(getSN(ip));
        System.out.println(verifySN(ip, snTxt));
        String ip2 = "192.168.1.104";
        System.out.println(verifySN(ip2, snTxt));*/
        System.out.println(getSN("BFEBFBFF000206A7001A3C4D5E6F"));
    }
}
